import { Context } from "koa";
import sha1 from "sha1";
import { config } from "../config/wechat";
class weChat {
  async connect(ctx: Context) {
    //ctx.query获取请求中携带的参数
    let token = config.wechat.token;
    //获取请求中的signature
    let signature = ctx.query.signature;
    //获取请求中的timestamp
    let timestamp = ctx.query.timestamp;
    //获取请求中的nonce
    let nonce = ctx.query.nonce;
    //获取请求中的echostr
    let echostr = ctx.query.echostr;
    //将Token，timestamp，nonce按字典排序,排序后链接成一个字符串
    let str = [token, timestamp, nonce].sort().join("");
    //使用sha1模块进行sha1加密
    let sha1Str = sha1(str);
    //判断加密后的字符串与请求中signature是否相等
    //如果相等返回echostr
    if (sha1Str === signature) {
      //将echostr返回给微信服务器
      ctx.body = echostr;
    } else {
      ctx.body = "wrong";
    }
  }
}
const wechat = new weChat();
export { wechat };
